package com.freshfresh.activity.shoppingcar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.freshfresh.activity.R;
import com.freshfresh.adapter.ShopLocalAdapter;
import com.freshfresh.adapter.ShopServerAdapter;
import com.freshfresh.utils.FreshConstants;
import com.freshfresh.utils.RequestManager;
import com.freshfresh.utils.UrlConstants;
import com.freshfresh.utils.Utils;
import com.freshfresh.view.db.DBManager;

//购物车

public class ShoppingCarActivity extends Activity implements Serializable{
	private ListView ptrl_shoppingCar;
	List<Map<String,Object>> listmap_local;
	List<Map<String,Object>> listmap_serve;
	private TextView tv_ac_shopping_car_main_total2;//总价格
	private TextView tv_ac_shopping_car_main_total;//总价格
	Dialog progressDialog;
	
	private TextView tv_title;
	private RelativeLayout rel_back;
	ShopServerAdapter adapter_server;
	ShopLocalAdapter localadapter;
	TextView tv_ac_shopping_car_main_goods_total;//数量
	//添加本地新商品
	private BroadcastReceiver br=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			listmap_local=new ArrayList<Map<String,Object>>();
			listmap_local=queryAllLocal();
			if(localadapter!=null){
				 localadapter.onDateChange(listmap_local);
			}else{
				 localadapter=new ShopLocalAdapter(ShoppingCarActivity.this, listmap_local,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
				 ptrl_shoppingCar.setAdapter(localadapter);
			}
		}
	};
	//更新 本地商品
	private BroadcastReceiver brupdate=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			listmap_local=new ArrayList<Map<String,Object>>();
			listmap_local=queryAllLocal();
			if(listmap_local!=null){
				localadapter.onDateChange(listmap_local);
			}else{
				 localadapter=new ShopLocalAdapter(ShoppingCarActivity.this, listmap_local,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
				 ptrl_shoppingCar.setAdapter(localadapter);
			}
		}
	};
	
	//已经登录后添加商品
		private BroadcastReceiver serveradd_br=new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				List<Map<String,Object>> listmap_serveNew=(List<Map<String,Object>>)arg1.getSerializableExtra("list");
				
				if(adapter_server!=null){
					adapter_server.onDateChange(listmap_serveNew);
				}else{
					adapter_server=new ShopServerAdapter(ShoppingCarActivity.this, listmap_serveNew,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
					ptrl_shoppingCar.setAdapter(adapter_server);	
				}
				
			}
		};
		
		//登录时更新本地购物车到服务器
				private BroadcastReceiver updatesp=new BroadcastReceiver() {
					
					@Override
					public void onReceive(Context arg0, Intent arg1) {
						List<Map<String,Object>> listmap_serveNew=(List<Map<String,Object>>)arg1.getSerializableExtra("list");
						
						if(adapter_server!=null){
							adapter_server.onDateChange(listmap_serveNew);
						}else{
							adapter_server=new ShopServerAdapter(ShoppingCarActivity.this, listmap_serveNew,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
							ptrl_shoppingCar.setAdapter(adapter_server);	
						}
						
					}
				};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ac_shopping_car_main);
		registerReceiver(br, new IntentFilter(FreshConstants.LOCAL_SHOPPINGCAR));
		registerReceiver(brupdate, new IntentFilter(FreshConstants.LOCAL_SHOPPINGCARUPDATE));
		registerReceiver(serveradd_br, new IntentFilter(FreshConstants.ADD_SERVER_SHOPPINGCAR));
		registerReceiver(updatesp, new IntentFilter(FreshConstants.UPDATELOCAL_SHOPPINGCAR));
		initView();
		initData();
	}
	
	
	public void initData(){
		if(FreshConstants.hasLogined(ShoppingCarActivity.this)){
			//已经登录了
			progressDialog.show();
			Cursor cursor=getAllPersonInfo();
			if(cursor.moveToNext()){
				Toast.makeText(ShoppingCarActivity.this, "本地有数据", 0).show();
				
				listmap_local=queryAllLocal();
				//同步本地数据库购物车到服务器
				List<Map<String,Object>> listmap=new ArrayList<Map<String,Object>>();
				for(int j=0;j<listmap_local.size();j++){
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("product_id", listmap_local.get(j).get("product_id").toString());
					map.put("bundle_id", "");
					map.put("qty", listmap_local.get(j).get("count").toString());
					listmap.add(map);
				}
				Log.e("listmap的长度是多少12380", listmap.size()+"");
				String strjson=JSON.toJSONString(listmap);
				Log.e("strjson是多少（（（（（（））））））", strjson);
				SharedPreferences share=FreshConstants.getUserShared(ShoppingCarActivity.this);
				 String userid=share.getString("userid", "");
				 String token=share.getString("token", "");
				
				Map<String, String> params = new HashMap<String, String>();
				params.put("store", "1");
				params.put("quoteid", "");
				params.put("token", token);
				params.put("customerid", userid);
				params.put("productsdata", strjson);
				
				
				Map<String,Object> map_obj=new HashMap<String, Object>();
				map_obj.put("customerid", userid);
				map_obj.put("store ", "1");
				map_obj.put("token ", token);
				map_obj.put("productsdata ", strjson);
				String str_mapobj=Utils.map2json(map_obj);
				
				params.put("cartProductAdd", str_mapobj);
				
				String ad_url = UrlConstants.AddShoppingCar;
				executeRequest(new StringRequest(ad_url, params,
						new Response.Listener<String>() {
							public void onResponse(String arg0) {
								progressDialog.dismiss();
								Log.e("listmap的……", arg0);
								if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
									Map<String,Object> map=(Map<String,Object>)Utils.parseJsonStr(arg0).get("data");
									
									tv_ac_shopping_car_main_total2.setText("总计： ¥"+map.get("base_grand_total").toString()+"");
						             tv_ac_shopping_car_main_total.setText("总计： ¥"+map.get("base_grand_total").toString()+"");
						             tv_ac_shopping_car_main_goods_total.setText("共"+map.get("product_total").toString()+"件商品");
						             
						             
									String quoteidstr=map.get("quoteid").toString();
									SharedPreferences share=FreshConstants.getUserShared(ShoppingCarActivity.this);
									share.edit().putString("quoteid", quoteidstr).commit();
									List<Map<String,Object>> listmap_serves=(List<Map<String,Object>>)map.get("product_info");
									if(adapter_server!=null){
										adapter_server.onDateChange(listmap_serves);
									}else{
										adapter_server=new ShopServerAdapter(ShoppingCarActivity.this, listmap_serves,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
										ptrl_shoppingCar.setAdapter(adapter_server);	
									}
									
									 String sql = "DELETE FROM " + "fresh_shoppingcar" +";";
									 DBManager.getDBconnection(ShoppingCarActivity.this).execSQL(sql);
								} 
							}

						}, new Response.ErrorListener() {

							public void onErrorResponse(VolleyError arg0) {
								progressDialog.dismiss();
								Toast.makeText(ShoppingCarActivity.this, "更新失败", 1).show();
							}
						}));
			}else{
				Toast.makeText(ShoppingCarActivity.this, "本地无数据", 0).show();
				
				
				SharedPreferences share=FreshConstants.getUserShared(ShoppingCarActivity.this);
				String userid=share.getString("userid", "");
				String token=share.getString("token", "");
				
				Map<String, String> params = new HashMap<String, String>();
				params.put("store", "1");
				params.put("quoteid", "");
				params.put("token", token);
				params.put("customerid", userid);
				String ad_url = UrlConstants.getShoppingCarInfo;
				Log.e("url是多少…………", ad_url);
				Log.e("token是多少…………", token);
				Log.e("userid是多少…………", userid);
				executeRequest(new StringRequest(ad_url, params,
						new Response.Listener<String>() {
							public void onResponse(String arg0) {
								progressDialog.dismiss();
								Log.e("listmap的……", arg0);
								if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
									Map<String,Object> map=(Map<String,Object>)Utils.parseJsonStr(arg0).get("data");
									tv_ac_shopping_car_main_total2.setText(map.get("base_grand_total").toString());
									tv_ac_shopping_car_main_total.setText(map.get("base_grand_total").toString());
									tv_ac_shopping_car_main_goods_total.setText(map.get("product_total").toString());
									
									String str_quoteid=map.get("quoteid").toString();
									SharedPreferences share=FreshConstants.getUserShared(ShoppingCarActivity.this);
									share.edit().putString("quoteid", str_quoteid).commit();
									listmap_serve=(List<Map<String,Object>>)map.get("product_info");
									if(adapter_server!=null){
										adapter_server.onDateChange(listmap_serve);
									}else{
										adapter_server=new ShopServerAdapter(ShoppingCarActivity.this, listmap_serve,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
										ptrl_shoppingCar.setAdapter(adapter_server);	
									}
									
								} else {
									
								}
							}

						}, new Response.ErrorListener() {

							public void onErrorResponse(VolleyError arg0) {
								// dialog.dismiss();
								Toast.makeText(ShoppingCarActivity.this, "获取失败", 1).show();
								progressDialog.dismiss();
							}
						}));
			}

			
		}else{
			//没有登录
			listmap_local=queryAllLocal();
			
			
			Cursor cursor=getAllPersonInfo();
			if(cursor.moveToNext()){
				Toast.makeText(ShoppingCarActivity.this, "没有登录本地有数据", 0).show();
			}else{
				Toast.makeText(ShoppingCarActivity.this, "没有登录本地无数据", 0).show();
			}
			
			if(listmap_local!=null){
				 localadapter=new ShopLocalAdapter(ShoppingCarActivity.this, listmap_local,tv_ac_shopping_car_main_goods_total,tv_ac_shopping_car_main_total2,tv_ac_shopping_car_main_total);
				ptrl_shoppingCar.setAdapter(localadapter);
				
			}
		}
	}

	public void initView() {
		listmap_local=new ArrayList<Map<String,Object>>();
		if (progressDialog == null) {
			progressDialog = Utils.createLoadingDialog(ShoppingCarActivity.this,
					"数据加载中……");
		}
		
		tv_ac_shopping_car_main_goods_total = (TextView) findViewById(R.id.tv_ac_shopping_car_main_goods_total);
		rel_back = (RelativeLayout) findViewById(R.id.rel_back);
		rel_back.setVisibility(View.GONE);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_title.setText("购物车");
		tv_ac_shopping_car_main_total = (TextView) findViewById(R.id.tv_ac_shopping_car_main_total);
		tv_ac_shopping_car_main_total2 = (TextView) findViewById(R.id.tv_ac_shopping_car_main_total2);
		ptrl_shoppingCar = (ListView) findViewById(R.id.ptrl_shoppingCar);
	}

	public Cursor getAllPersonInfo() {
		return DBManager.getDBconnection(ShoppingCarActivity.this).query("fresh_shoppingcar", new String[] {"product_id", "picurl", "name", "stock","price","count" }, null, null, null, null, null);
	}
	public List<Map<String,Object>> queryAllLocal(){
		Cursor cursor=getAllPersonInfo();
		int totalprice=0;
		int totalcount=0;
		 if (cursor.moveToFirst() == true)  
         {  
             String str = "";  
               
             for (int index=0; index<cursor.getCount(); index++)  
             {  
            	 Map<String,Object> map=new HashMap<String, Object>();
            	 String product_id = cursor.getString(cursor.getColumnIndex("product_id"));  
                 String picurl = cursor.getString(cursor.getColumnIndex("picurl"));  
                 String name = cursor.getString(cursor.getColumnIndex("name"));  
                 String stock = cursor.getString(cursor.getColumnIndex("stock"));  
                 String price = cursor.getString(cursor.getColumnIndex("price"));  
                 String count = cursor.getString(cursor.getColumnIndex("count"));  
                 map.put("product_id", product_id);
                 map.put("picurl", picurl);
                 map.put("name", name);
                 map.put("stock", stock);
                 map.put("price", price);
                 map.put("count", count);
                 listmap_local.add(map);
                 
                 //计算价格 数量*单价
//                 float count=Float.parseS(count);
                 float mycount=Float.parseFloat(count);
                 float myprice=Float.parseFloat(price);
                 totalprice+=mycount*myprice;
                 totalcount+=mycount;
                 cursor.moveToNext();  
             }  
             cursor.close();  
             tv_ac_shopping_car_main_total2.setText("总计： ¥"+totalprice+"");
             tv_ac_shopping_car_main_total.setText("总计： ¥"+totalprice+"");
             tv_ac_shopping_car_main_goods_total.setText("共"+totalcount+"件商品");
         }  
         else  
         {  
        	 totalprice=0;
        	 tv_ac_shopping_car_main_total2.setText("总计： ¥"+"0");
        	 tv_ac_shopping_car_main_total.setText("总计： ¥"+"0");
        	 tv_ac_shopping_car_main_goods_total.setText("共0件商品");
        	 Toast.makeText(ShoppingCarActivity.this, "暂无商品", 0).show();
        	 
         }  
		return listmap_local;
	}
	
	protected void executeRequest(Request request) {
		RequestManager.addRequest(request, this);
	}
}
